package com.tfswue.dyq.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
//开启websecurity配置
@EnableWebSecurity
public class SecurityConfig {
    //配置密码加密器（必需）
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//使用BCrypt密码加密
    }
    //配置用户存储（内容方式，生产环境需连接数据库）
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("pass"))
                .roles("USER")
                .build();

        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin"))
                .roles("ADMIN","USER")
                .build();

        return new InMemoryUserDetailsManager(user, admin);
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/","index").permitAll()//允许根路径匿名访问
                        .requestMatchers("/public/**").permitAll()//公开路径无需认证
                        .requestMatchers("/admin/**").hasRole("ADMIN")//仅管理员可访问
                        .anyRequest().authenticated()//其他所有请求需认证
                )
                .formLogin(from -> from
                        .loginPage("/index.html")
                        .loginProcessingUrl("/login")
                        .defaultSuccessUrl("/public/hello")
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutUrl("/public/goodbye")
                        .permitAll()
                )
                .csrf(csrf -> csrf.disable()); // 禁用CSRF保护（仅用于演示，生产环境中请谨慎使用）

        return http.build();
    }

}
